<template>
	<div>
		<div>
			<!-- 标题栏 -->
			<div class="tool-bar-fixed" ref="mapTop" :style="{top:'2rpx'}">
				<div class="search_view">
					<image class="search_icon" src="http://images.linglinggong.net/icon1/44.png"></image>
					<input class="search_input" placeholder-class="search_inputp" placeholder="搜索您需要的工作地点(可拖动地图)"
						@focus="onfocus" @input="searchAddress" v-model="searchvalue" />
				</div>
			</div>
			<!-- 标题栏 -->
			<!-- #ifdef MP-WEIXIN -->
			<map id="map" ref="map" @regionchange="regionchange" :markers="markers" :controls="controls"
				:longitude="location.longitude" :latitude="location.latitude" :scale="18"
				:style="{ height:mapStyle.height, width: '750rpx' ,marginTop:mapStyle.marginTop}"
				@controltap="handleControl">
				<!-- 地图中心点标记 -->
				<image class="cover_marker" src="http://images.linglinggong.net/wgc_icon/dingwei.png"
					:style="{left:mapWAH.left,top:mapWAH.top}" v-if="mapStyle.height"></image>
				<!-- 定位控件 -->
				<image class="do_get_location" src="http://images.linglinggong.net/wgc_icon/10.png"
					@click="handleBackLocation"></image>
			</map>
			<!-- #endif -->
			<!-- #ifdef MP-ALIPAY || MP-TOUTIAO -->
			<view class="map" :style="{ height:mapStyle.height, width: '750rpx' ,marginTop:mapStyle.marginTop}">
				<map id="map" ref="map" @regionchange="regionchange" :markers="markers" :controls="controls"
					:longitude="location.longitude" :latitude="location.latitude" :scale="18"
					:style="{ height:mapStyle.height, width: '750rpx'}" @controltap="handleControl">
				</map>
				<!-- 地图中心点标记 -->
				<image class="cover_marker" src="http://images.linglinggong.net/wgc_icon/dingwei.png"
					:style="{left:mapWAH.left,top:mapWAH.top}" v-if="mapStyle.height"></image>
				<!-- 定位控件 -->
				<image class="do_get_location" src="http://images.linglinggong.net/wgc_icon/10.png"
					@click="handleBackLocation"></image>
			</view>
			<!-- #endif -->
			<!-- 底部下单 -->
			<div class="main_bottom" ref="mapBottom" @click="handleChooseLocation">
				<div class="choose_address">
					<text class="add_text">{{addressText}}</text>
				</div>
				<text class="uni-btn-v">选择这里</text>
			</div>
			<!-- 底部下单 -->
			<!-- #ifdef MP-WEIXIN || MP-TOUTIAO  -->
			<!-- 历史列表 -->
			<div v-if="showHistoryView" class="search_list_view" :style="{top:demo.height+demo.top+topHeight+'px'}">
				<div class="HistoryViewTitle">
					<span>历史搜索</span>
					<image class="HistoryViewImge" src="http://images.linglinggong.net/wgc_icon/18.png"
						@click="delHistory"></image>
				</div>
				<!-- <div style=""> -->
				<div class="HistoryList">
					<div class="HistoryList-Item" v-for="(item,index) in historyAdd" :key="index">
						<text class="HistoryList-Item-span" @click="chooseIs(index,item)">{{item.name}}</text>
					</div>
				</div>
			</div>
			<!-- 搜索出来的地址 -->
			<view>
				<view show-scrollbar="true" v-if="showListView" class="search_list_view"
					:style="{top:demo.height+demo.top+topHeight+'px'}">
					<view v-for="(item,index) in addressList" :key="item.id" class="addres_item"
						@click="chooseIs(index,item)">
						<text class="text_name">{{item.name}}</text><br />
						<text class="text_address">{{item.district+item.address}}</text>
						<image class="choose_icon" v-if="addressIndex===index"
							src="http://images.linglinggong.net/icon1/01.png"></image>
					</view>
				</view>
			</view>
			<!-- 搜索出来的地址 -->
			<!-- #endif -->
		</div>
	</div>
</template>
<script>
	const amapFile = require('@/common/amap-wx.js');
	import unit from '../../libs/newUnit.js'
	var myAmapFun = new amapFile.AMapWX({
		key: '3d6771af06c8fe3e2e9dfd2f8eec2cb1'
	});
	var mapContext = null;
	import {
		inputtips
	} from '@/api/api.js' //输入提示功能
	export default {
		data() {
			return {
				searchvalue: '', //查询值
				iStatusBarHeight: 0,
				mapStyle: {
					height: '',
					marginTop: ''
				},
				mapWAH: {
					left: 0,
					top: 0
				},
				markers: [],
				controls: [],
				location: {
					"latitude": 0,
					"longitude": 0
				}, //地图中心经纬度
				latitude: '', //选中的新定位
				longitude: '', //选中的新定位
				addressText: "暂未定位成功，请稍候···",
				addressList: [],
				addressIndex: '',
				addressItem: {},
				showListView: false,
				showHistoryView: false,
				region: '', //街道行政代码
				type: '', //send, map
				historyAdd: [], //历史地址数组
				timer: '',
				topHeight: 0,
				bottomHeight: 0,
				demo: {
					top: 0,
					height: 0
				},
				hasLocation: false
			};
		},
		onReady() {
			// #ifdef MP-WEIXIN || MP-TOUTIAO 
			this.MP_selectQuery()
			// #endif
			// #ifdef MP-ALIPAY
			this.MPALIPAY_selectQuery()
			// #endif
		},
		methods: {
			/* 搜索设置location */
			setLocation(e) {
				this.location = e
			},
			/* 搜索框聚焦事件 */
			onfocus() {
				// #ifdef MP-WEIXIN || MP-TOUTIAO
				this.showHistoryView = true
				// #endif
				// #ifdef MP-ALIPAY
				uni.navigateTo({
					url: '/pages/chooseLocation/chooseLocationSearch/chooseLocationSearch'
				})
				// #endif
			},
			/* 支付宝小程序设置地图大小 */
			MPALIPAY_selectQuery() {
				var mapStyle = this.mapStyle
				console.log('进来了------------------')
				uni.getSystemInfo({
					success: res => { // res - 各种参数
						console.log(res)
						var winWidth = res.windowWidth
						var winHeight = res.windowHeight
						my.createSelectorQuery().select('.tool-bar-fixed').boundingClientRect().select(
							'.main_bottom').boundingClientRect().exec((res) => {
							console.log(res);
							var topHeight = res[0].height;
							this.topHeight = topHeight;
							var bottomHeight = res[1].height;
							var mapheight = (winHeight - topHeight - bottomHeight)
							mapStyle.height = mapheight + 'px'
							mapStyle.marginTop = topHeight + 'px'
							this.mapStyle = mapStyle
							this.mapWAH.top = (mapheight / 2 - 30) + 'px'
							this.mapWAH.left = (winWidth / 2 - 10) + 'px'
						})
					}
				});
			},
			/* 查询节点设置地图大小 */
			MP_selectQuery() {
				var mapStyle = this.mapStyle
				console.log('进来了------------------')
				uni.getSystemInfo({
					success: res => { // res - 各种参数
						console.log(res)
						var winWidth = res.windowWidth
						var winHeight = res.windowHeight
						uni.createSelectorQuery().in(this).select('.tool-bar-fixed').boundingClientRect(
							result => {
								if (result) {
									console.log(result)
									var topHeight = result.height;
									this.topHeight = topHeight;
									uni.createSelectorQuery().in(this).select('.main_bottom')
										.boundingClientRect(res => {
											if (res) {
												var bottomHeight = res.height;
												var mapheight = (winHeight - topHeight - bottomHeight)
												mapStyle.height = mapheight + 'px'
												mapStyle.marginTop = topHeight + 'px'
												this.mapStyle = mapStyle
												this.mapWAH.top = (mapheight / 2 - 30) + 'px'
												this.mapWAH.left = (winWidth / 2 - 10) + 'px'
											}
										}).exec();
								}
							}).exec();
					}
				});
			},
			// 点击控件时触发移动到当前定位，右下角方圆形
			handleControl() {
				this.handleBackLocation()
			},
			//删除历史记录
			delHistory() {
				uni.setStorageSync("historyAdd", [])
				this.historyAdd = []
			},
			//按照idnex删除
			delHistoryOfindex(index) {
				this.historyAdd.splice(index, 1)
				uni.setStorageSync("historyAdd", this.historyAdd)
			},
			// 输入提示功能
			async searchAddress(e) {
				this.showHistoryView = false
				let city = uni.getStorageSync('region').slice(0, 6)
				let keys = ["0b101f877221741f6eeb451bda577878", "f5477d0e2bc4a59b958f3d80c885c236",
					"d73cc951a96637a251a9a2446b48ce9c"
				]
				for (let i = 0; i < keys.length; i++) {
					let breck = true
					let res = await inputtips({
						location: this.location.longitude + ',' + this.location.latitude,
						keywords: this.searchvalue,
						city: city,
						citylimit: true,
						key: keys[i]
					})
					if (res[1].data.infocode == 10000) {
						this.addressList = res[1].data.tips
						this.showListView = true
						break
					}
				}
			},
			onbackBtn() {
				uni.hideKeyboard()
				if (this.showHistoryView || this.showListView) {
					this.showHistoryView = false
					this.showListView = false
				} else {
					uni.navigateBack()
				}
			},
			// 填写搜索地址，移动地图
			chooseIs(index, bodyInfoList) {
				uni.hideKeyboard()
				uni.showLoading({
					title: '请稍候···'
				})
				console.log(bodyInfoList)
				if (!this.historyAdd.includes(bodyInfoList)) {
					this.historyAdd.push(bodyInfoList)
					uni.setStorageSync("historyAdd", this.historyAdd)
				}
				if (bodyInfoList.location == '' || bodyInfoList.location == null) {
					uni.hideLoading()
					return uni.showToast({
						title: "请选择其他地址~",
						icon: "none"
					})
				}
				this.addressIndex = index
				this.addressItem = bodyInfoList
				var that = this
				that.addressIndex = ''
				that.showListView = false
				that.showHistoryView = false
				// 选择完成之后移动地图到指定位置
				this.location = {
					longitude: bodyInfoList.location.split(',')[0],
					latitude: bodyInfoList.location.split(',')[1]
				}
				that.addressIndex = ''
				that.showListView = false
				uni.hideLoading()
			},
			// 改变位置时，由经纬度，得到具体地址
			regionchange(e) {
				if (e.type == "end") {
					mapContext.getCenterLocation({
						success: res => {
							this.getAddressText(res)
						}
					})
				} else if (e.type == "regionchange") {
					mapContext.getCenterLocation({
						success: res => {
							this.getAddressText(res)
						}
					})
				}
			},
			//由经纬度，得到具体地址
			getAddressText(point) {
				this.latitude = point.latitude
				this.longitude = point.longitude
				console.log(9898);
				this.getAdcode(point) //由经纬度获取街道代码
				// var that = this
				myAmapFun.getRegeo({
					location: `${point.longitude},${point.latitude}`,
					success: data => {
						//成功回调
						this.addressText = data[0].regeocodeData.formatted_address
					},
					fail: function(info) {
						//失败回调
						console.log(88, info)
					}
				})
			},
			// 检查授权
			doCheckPermission() {
				this.getSetting();
			},
			// 得到定位
			doGetLocation() {
				uni.showLoading({
					title: "定位中···"
				})
				uni.getLocation({
					// #ifdef MP-WEIXIN
					type: 'gcj02',
					altitude: true,
					// #endif
					geocode: true,
					success: (res) => {
						this.hasLocation = true;
						this.location = res;
						this.getAddressText({
							latitude: res.latitude,
							longitude: res.longitude
						})
						var marker = {
							latitude: res.latitude,
							longitude: res.longitude,
							callout: {
								content: '我的位置',
								bgColor: '#ffffff',
								padding: 8,
								fontSize: 14,
								display: 'ALWAYS'
							},
						}
						var markers = []
						markers.push(marker)
						this.markers = markers
						uni.hideLoading()
					},
					fail: (err) => {
						console.log(err)
					}
				})
			},
			// 回到用户当前位置
			handleBackLocation() {
				this.location.latitude = this.markers[0].latitude
				this.location.longitude = this.markers[0].longitude
			},
			// 判断用户是否授权
			getSetting() {
				uni.getSetting({
					success: (res) => {
						if (res.authSetting['scope.userLocation'] != undefined && res.authSetting[
								'scope.userLocation'] != true) { //非初始化进入该页面,且未授权
							uni.showModal({
								title: "尊敬的找零工用户",
								content: "使用本APP需要定位权限，才能正常使用！",
								confirmText: "去设置",
								success: res => {
									if (res.cancel) {
										uni.showToast({
											title: '授权失败',
											icon: 'none',
											duration: 1000
										})
									} else if (res.confirm) {
										this.openSet()
									}
								}
							})
						} else {
							this.doGetLocation();
						}
					}
				})
			},
			/* 打开设置 */
			openSet() {
				uni.openSetting({
					success: dataAu => {
						if (dataAu.authSetting["scope.userLocation"] == true) {
							uni.showToast({
								title: '授权成功',
								icon: 'success',
								duration: 1000
							})
							this.doGetLocation();
						} else {
							uni.showToast({
								title: '授权失败',
								icon: 'none',
								duration: 1000
							})
						}
					}
				})
			},
			// 由经纬度查询街道的行政代码
			getAdcode(point) {
				uni.request({
					url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
					data: {
						key: 'd73cc951a96637a251a9a2446b48ce9c',
						location: point.longitude + ',' + point.latitude
					},
					success: res => {
						// console.log(99912,res);
						this.region = res.data.regeocode.addressComponent.towncode
						// console.log(113,this.region);
					},
					fail: (err) => {
						console.log('err', err);
					}
				})
			},
			// 用户选择的位置，回调至前页
			handleChooseLocation() {
				let reg = /.+?(省|市|自治区|自治州|县|区|街道|镇|乡|号)/g;
				let detailStreet = this.addressText.slice((this.addressText.match(reg)[0] + this.addressText.match(reg)[
					1] + this.addressText.match(reg)[2] + this.addressText.match(reg)[3]).length)
				console.log(this.addressText, '拼接')
				clearTimeout(this.timer)
				this.timer = setTimeout(() => {
					uni.navigateBack({
						delta: 1
					})
					let pages = getCurrentPages(); //获取页面栈
					let prevPage = pages[pages.length - 2]; //上一页页面实例
					prevPage.$vm.getChooseLocation(this.addressText.match(reg)[2] + '·' + this.addressText.match(
						reg)[3] + '·' + detailStreet, this.latitude, this.longitude, this.region); //前一个页面方法
				}, 500)
			},
			/* 获取小程序导航栏的高度 */
			getMenuBar() {
				const demo = uni.getMenuButtonBoundingClientRect()
				this.demo.top = demo.top
				this.demo.height = demo.height
			},
		},
		onLoad(e) {
			this.type = e.type
			this.doCheckPermission()
			mapContext = uni.createMapContext('map')
			if (uni.getStorageSync("historyAdd")) {
				this.historyAdd = uni.getStorageSync("historyAdd")
			}
			unit.get_task_Latitude().then(v => {
				if (!v.code) {
					this.location.latitude = v.split(',')[0]
					this.location.longitude = v.split(',')[1]
				}
			})
			// #ifdef MP-WEIXIN || MP-TOUTIAO
			this.getMenuBar()
			// #endif
		}
	};
</script>
<style lang="less" scoped>
	/* 标题 */
	.tool-bar-fixed {
		background-color: #FFFFFF;
		position: fixed;
		left: 0;
		right: 0;
		padding: 20upx 40upx;
		z-index: 1;
	}

	.demo {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		background: #fff;
		font-size: 26rpx;

		.left {
			float: left;
			position: absolute;
			width: max-content;
			height: max-content;
			top: 0;
			bottom: 0;
			left: 0;
			padding-left: 20rpx;
			width: 100rpx;
			margin: auto;

			image {
				width: 19rpx;
				height: 32rpx;
			}
		}
	}

	.search_view {
		flex-direction: row;
		display: flex;
		background-color: #F2F2F2;
		border-radius: 36upx;
	}

	.search_input {
		height: 80upx;
		line-height: 80upx;
		flex: 1;
		font-size: 32upx;
		background: transparent;
	}

	.search_inputp {
		height: 80upx;
		line-height: 80upx;
		flex: 1;
		font-size: 14wx;
	}

	.map {
		position: relative;
	}

	.search_icon {
		width: 28upx;
		height: 28upx;
		margin: 26upx;
	}

	/* 搜索列表 */
	.search_list_view {
		position: fixed;
		top: 98upx;
		bottom: 0upx;
		left: 0upx;
		right: 0upx;
		padding-top: 35upx;
		z-index: 100;
		background-color: #FFF;
		box-sizing: border-box;
		padding: 10rpx;
	}

	.addres_item {
		padding: 10upx 40upx;
		border-bottom: 1rpx solid #FCC928;
	}

	.text_name {
		font-size: 36upx;
		line-height: 50upx;
	}

	.text_address {
		font-size: 30upx;
		line-height: 40upx;
	}

	.choose_icon {
		position: absolute;
		top: 30upx;
		right: 30upx;
		width: 50upx;
		height: 50upx;
	}

	/* 中心点 */
	.cover_marker {
		position: absolute;
		z-index: 99;
		width: 44rpx;
		height: 71rpx;
	}

	/* 定位 */
	.do_get_location {
		position: absolute;
		z-index: 99;
		width: 92rpx;
		height: 96rpx;
		right: 30rpx;
		bottom: 30rpx;
	}

	/* 底部下单 */
	.main_bottom {
		position: fixed;
		bottom: 0upx;
		left: 0upx;
		right: 0upx;
		background-color: #FFFFFF;
		height: 260upx;
	}

	.choose_address {
		margin: 20upx 40upx 20upx 40upx;
		padding: 10upx;
	}

	.add_text {
		font-size: 32upx;
		line-height: 55upx;
	}

	.uni-btn-v {
		position: absolute;
		left: 40upx;
		right: 40upx;
		bottom: 20upx;
		background-color: #FCC928;
		border-radius: 10upx;
		height: 80upx;
		line-height: 80upx;
		font-size: 36upx;
		color: #402110;
		text-align: center;
	}

	/* .repair_type{height: 80upx;display: flex;justify-content:center;}
.repair_type_item{height: 80upx;line-height: 80upx;width: 200upx;font-size: 30upx;text-align: center;}
.activity{color: #FCC928;}
.choose_address{margin: 20upx 40upx 20upx 40upx;height: 80upx; width: calc(100% - 80upx); border-style:solid;border-width:1upx;border-color:#ff0000;border-radius:5px;}
.add_icon{width: 40upx;height: 40upx;margin: 20upx;float: left;}
.add_text{font-size: 32upx;line-height: 80upx;float: left;width: calc(100% - 80upx);}
.uni-btn-v{margin:20upx 40upx 20upx 40upx;background-color: #FCC928;border-radius: 10upx;height: 80upx;line-height: 80upx;font-size: 34upx;color: #FFFFFF;text-align: center;}*/
	.HistoryViewTitle {
		font-size: 28upx;
		width: 690upx;
		height: 40upx;
		margin-top: 0upx;
		margin-left: 30upx;
	}

	.HistoryViewButton {
		width: 534upx;
		height: 78upx;
		background: #FCC928;
		border-radius: 8upx;
		font-size: 32upx;
		font-weight: bold;
		color: #402110;
		margin-left: 108upx;
		justify-content: center;
		align-items: center;
		margin-top: 40upx;
	}

	.HistoryViewImge {
		width: 36rpx;
		height: 36rpx;
		position: absolute;
		right: 0;
	}

	.HistoryList {
		width: 690upx;
		margin-left: 30upx;
		margin-top: 24upx;
		flex-direction: row;
		flex-wrap: wrap;
	}

	.HistoryList-Item {
		/* width: 690upx; */
		background-color: #F2F2F2;
		margin-top: 24upx;
		margin-left: 20upx;
		border-radius: 8rpx;
		padding: 10rpx 10rpx;
		display: inline-block;
	}

	.HistoryList-Item-lin {
		width: 32rpx;
		height: 32rpx;
		position: absolute;
		left: 0;
	}

	.HistoryList-Item-del {
		width: 32rpx;
		height: 32rpx;
		position: absolute;
		right: 0;
	}

	.HistoryList-Item-span {
		font-size: 28rpx;
		font-weight: 500;
		color: #000000;
		padding: 20rpx;
	}
</style>